package com.heima.wemedia.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 创建拦截器
 */
@Component
public class WmTokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头
        String userId = request.getHeader("userId");

        //2. 存入线程
        if (StringUtils.isNotBlank(userId)) {
            WmThreadLocalUtil.setId(Long.valueOf(userId));
            return super.preHandle(request, response, handler);
        }
        //3.请求头为空,响应错误信息
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除线程
        WmThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
